#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
using namespace std;
typedef void (*work_t)(int);    //函数指针
typedef void (*task_t)(int, pid_t); //函数指针 参数便于打印日志
#define TASK_NUM 3
void PrintLog(int fd, pid_t pid)
{
    cout << "sub process: " << pid << ", fd: " << fd << ", task:printf log task\n" << endl;
}

void ReloadConf(int fd, pid_t pid)
{
   cout << "sub process: " << pid << ", fd: " << fd << ", task:reload conf task\n" << endl;
}

void ConnectMysql(int fd, pid_t pid)
{
   cout << "sub process: " << pid << ", fd: " << fd << ", task:connect mysql task\n" << endl;
}
task_t task[TASK_NUM] = {PrintLog, ReloadConf, ConnectMysql};

// 子进程从管道中读取任务
void Worker(int fd) 
{
    // 从0读取任务（管道被重定向为0）
    while (true)
    {
        uint32_t command_code = -1;
        ssize_t rfd = read(0, &command_code, sizeof(command_code));
        if (rfd == sizeof(command_code))
        {
            task[command_code](fd, getpid());
        }
        else if (rfd == 0)
        {
            cout << "sub process " << getpid() << " quit now..." << endl;
            break;
        }
    }
}

uint32_t NextTask()
{
    return rand() % TASK_NUM;
}